#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

// Function to check if the IP address is valid
int isValidIP(const char *ip) {
    int num, dots = 0;
    char *ptr, *ipCopy;

    // Make a non-const copy of the IP string to be used by strtok
    ipCopy = strdup(ip); // Be sure to free this later to avoid memory leaks

    if (ipCopy == NULL) {
        perror("strdup failed");
        return 0;
    }

    ptr = strtok(ipCopy, ".");
    if (ptr == NULL) {
        free(ipCopy); // Don't forget to free the allocated memory
        return 0;
    }

    while (ptr) {
        // Check if the segment is a number and less than 256
        num = atoi(ptr);
        if (num >= 256 || num < 0) {
            free(ipCopy); // Free the allocated memory before returning
            return 0;
        }

        // Move to the next token (next segment)
        ptr = strtok(NULL, "."); // 最后一个是dots==3,此时ptr == NULL

        if (ptr != NULL) {
            dots++;
	    printf("d=%d ptr=%s\n", dots, ptr); 
	}

        // There must be exactly 3 dots
        if (dots > 3) {
            free(ipCopy); // Free the allocated memory before returning
            return 0;
        }
    }
    free(ipCopy); // Free the allocated memory before returning

    return (dots == 3) ? 1 : 0;
}

// Function to convert IP address to 32-bit integer
unsigned int ipToInt(const char *ip) {
    unsigned int i, istr = 0;
    char *ptr;
    char ipCopy[16];

    // Copy the IP address to avoid modifying the original string
    strcpy(ipCopy, ip);

    ptr = strtok(ipCopy, ".");

    for (i = 0; i < 4; i++) {
        istr += atoi(ptr) * pow(256, 3 - i);
        ptr = strtok(NULL, ".");
    }

    return istr;
}

int main() {
    char *ip = "5.6.7.8";

    if (!isValidIP(ip)) {
        printf("Input is invalid!\n");
        return -1;
    }

    unsigned int istr = ipToInt(ip);
    printf("Integer representation of IP: %u\n", istr);

    return 0;
}
